package com.zhenhunfan.hello.rpc.demo06;

import com.zhenhunfan.hello.rpc.common.IUserService;
import com.zhenhunfan.hello.rpc.common.User;
import com.zhenhunfan.hello.rpc.common.UserServiceImpl;
import com.zhenhunfan.hello.rpc.demo06.utils.ClassUtils;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

/**
 * <p>Title: Server</p>
 * <p>Description: </p>
 *
 * @author zhenhunfan
 * @version 1.0.0
 * @date 2021/4/8
 */
public class Server {
    public static boolean running = true;

    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(9000);
        while(running){
            Socket s = ss.accept();
            process(s);
            s.close();
        }
        ss.close();
    }

    private static void process(Socket s) throws Exception {
        InputStream in = s.getInputStream();
        OutputStream out = s.getOutputStream();
        ObjectInputStream ois = new ObjectInputStream(in);
        ObjectOutputStream oos = new ObjectOutputStream(out);

        //接收客户端发送过来的方法详情，通过反射调用相关方法，并返回客户端数据
        String className = ois.readUTF();
        String methodName = ois.readUTF();
        Class[] parameterTypes = (Class[]) ois.readObject();
        Object[] args = (Object[]) ois.readObject();

        //从服务注册表找到具体的类,也可以通过Spring @Autowired 去注入一个具体类对象
        Class clazz = Class.forName(className);
        List<Class<?>> allClassByInterface = ClassUtils.getAllClassByInterface(clazz);

        Class clazz2 = allClassByInterface.get(0);
        Method method = clazz2.getMethod(methodName, parameterTypes);
        Object o = method.invoke(clazz2.newInstance(), args);

        oos.writeObject(o);
        oos.flush();
    }
}
